<script setup>
import {ajax} from 'framework'
import {ref} from 'vue'
import {message} from 'heyui'

const ds = ref()
const reloading = ref(false)

function reboot() {
  reloading.value = true
  ajax.get('plugins/restart').then(r => {
    let id = r.data
    let requestContextId = () => {
      let success = false
      ajax.post('plugins/context_id').then(r => {
        if (r.data != id) {
          reloading.value = false
          location.reload()
        } else {
          setTimeout(requestContextId, 1000)
        }
      }).catch(e => {
        setTimeout(requestContextId, 1000)
      })
    }
    setTimeout(requestContextId, 1000)
  }).catch(e => {
    if (e.code == 100) {
      reloading.value = false
    } else {
      let requestContextId = () => {
        let success = false
        ajax.post('plugins/context_id').then(r => {
          location.reload()
        }).catch(e => {
          setTimeout(requestContextId, 1000)
        })
      }
      setTimeout(requestContextId, 1000)
    }
  })

}

const formatDisabled = (v) => {
  return v ? '已禁用' : '已启用'
}
const enablePlugin = (v, enable) => {
  ajax.formPost('plugins/enable', {id: v.id, enable}).then(r => {
    ds.value.reload()
  })
}
const installForm = ref(null)
let installJar = null
const installPlugin = (f) => {
  console.log(f)
  if (f.name.endsWith(".zip")) {
    ajax.upload('plugins/install', {file: f}).then(r => {
      message("安装成功,请重启系统")
      ds.value.reload()
    })
  } else if (f.name.endsWith(".jar")) {
    installJar = f
    let jarName = f.name.replace(/\.jar$/, '');
    let idx = jarName.indexOf("-")
    let id = jarName, version = "1.0"
    if (idx > 0) {
      id = jarName.substring(0, idx);
      version = jarName.substring(idx + 1)
    }
    installVisible.value = true;
    installData.value = {
      id, version, name: "",author:'',description: ''
    }
  } else {
    message("不支持的文件格式")
  }

}
const uploading = ref(false)
const installJarPlugin = () => {
  let validResult = installForm.value.valid()
  if (validResult.result) {
    uploading.value = true
    ajax.upload('plugins/install_jar', {
      id: installData.value.id,
      name: installData.value.name,
      version: installData.value.version,
      description:installData.value.description,
      author:installData.value.author,
      file: installJar
    }).then(r => {
      message("安装成功,请重启系统")
      installData.value = null
      installVisible.value = false
      installJar = null
      ds.value.reload()
    }).finally(_ => {
      uploading.value = false
    })
  }
}
const uninstall = (f) => {
  ajax.formPost('plugins/uninstall', {id: f.id}).then(r => {
    message("应用已卸载,请重启系统")
    ds.value.reload()
  })
}
const version = ref('unknown'),startTime=ref('')
ajax.get('plugins/application_info').then(r => {
  version.value = r.data.frameWorkVersion;
  startTime.value = r.data.lastStartTime;
})
const fileChoose=(accept)=>{
  return new Promise((resolve)=>{
    let input = document.createElement("input")
    input.type='file'
    if(accept)
      input.accept=accept
    input.onchange=function(e){
      resolve(e.target.files[0])
    }
    input.oncancel=function(){
      input=null;
    }
    input.click()
  })
}
const updateFile=(data)=>{
  fileChoose().then(f=>{
    message("文件上传中，请稍后...")
    ajax.upload('plugins/upload_file', {
      appid: data.id,
      file: f
    }).then(r => {
      message("文件已经更新")
    })
  })
}
const installData = ref(null)
const installVisible = ref(false)
</script>
<template>
  <DataTable url="plugins/list" ref="ds">
    <template #tools="table">
      <Button :loading="reloading" icon="icon-reload" color="red" @click="reboot">重启系统</Button>
      <Space/>
      <FileInput accept=".zip,.jar" @change="installPlugin">
        <Button color="primary">安装应用</Button>
      </FileInput>

    </template>
    <template #default="table">
      <Table :datas="table.data" ref="tb" :loading="table.loading">
        <TableItem prop="id" title="ID"></TableItem>
        <TableItem prop="name" title="名称"></TableItem>
        <TableItem prop="version" title="版本"></TableItem>
        <TableItem prop="author" title="作者"></TableItem>
        <TableItem prop="description" title="说明"></TableItem>
        <TableItem prop="disabled" :format="formatDisabled" title="状态"></TableItem>
        <TableItem title="操作" :width="180" fixed="right">
          <template #default="{data}">
            <Poptip v-if="data.disabled" content="确定要启用该应用吗？" @confirm="enablePlugin(data,true)">
              <span class="link">启用</span>
            </Poptip>
            <Poptip v-else content="确定要禁用该应用吗？" @confirm="enablePlugin(data,false)">
              <span class="link">禁用</span>
            </Poptip>
            <Divider direction="vertical"/>
            <Poptip content="确定要卸载该应用吗？" @confirm="uninstall(data)">
              <span class="link">卸载</span>
            </Poptip>
            <Divider direction="vertical"/>
            <span class="link" @click="updateFile(data)">文件更新</span>
          </template>
        </TableItem>
      </Table>
    </template>
    <template #bottom>
         <span style="float:right;line-height:32px;">
        启动时间：{{startTime}}
        框架版本：{{ version }}
      </span>
    </template>
  </DataTable>
  <Modal v-model="installVisible" title="安装应用" :closeOnMask="false" hasDivider hasCloseIcon>
    <Form :model="installData" :rules="{}" ref="installForm">
      <FormItem label="应用名称" prop="name" required>
        <Input v-model="installData.name"/>
      </FormItem>
      <FormItem label="应用ID" prop="id" required>
        <Input v-model="installData.id"/>
      </FormItem>
      <FormItem label="应用版本" prop="version" required>
        <Input v-model="installData.version"/>
      </FormItem>
      <FormItem label="作者" prop="author">
        <Input v-model="installData.author"/>
      </FormItem>
      <FormItem label="说明" prop="description">
        <Textarea v-model="installData.description"/>
      </FormItem>
    </Form>
    <template #footer>
      <Button @click="installVisible=false">取消</Button>
      <Button color="primary" :loading="uploading" @click="installJarPlugin">确定</Button>
    </template>
  </Modal>
</template>
